// 确保在DOM加载完成后执行Vue应用初始化
document.addEventListener('DOMContentLoaded', () => {
    const { createApp } = Vue;
    
    createApp({
        data() {
            return {
                // 标签页状态
                activeTab: 'file',
                // 分类相关
                categories: [],
                selectedCategory: '',
                // 文件上传相关
                files: null,
                fileStatus: '',
                fileStatusColor: '',
                fileUploading: false,
                // 文本嵌入相关
                textContent: '',
                textStatus: '',
                textStatusColor: '',
                textEmbedding: false,
                // 图片嵌入相关
                imageFiles: [],
                imageDescription: '',
                imageStatus: '',
                imageStatusColor: '',
                imageEmbedding: false,
                // 网页URL相关
                webUrls: '',
                urlStatus: '',
                urlStatusColor: '',
                urlParsing: false,
                // 错误处理
                showError: false,
                errorMessage: '',
                // 加载状态
                loading: false,
                // 存储已上传文件的信息
                uploadedFiles: [],
                savedTextFiles: [],
                uploadedImages: [],
                parsedUrls: []
            }
        },
        methods: {
            // 加载分类列表
            loadCategories() {
                this.loading = true;
                fetch('/get_category')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.category_list && data.category_list.length > 0) {
                            this.categories = data.category_list;
                            
                            // 查找default分类
                            const defaultCategory = data.category_list.find(cat => cat.name === 'default');
                            if (defaultCategory) {
                                this.selectedCategory = defaultCategory.name;
                            } else if (data.category_list.length > 0) {
                                // 如果没有default分类，默认选中第一个
                                this.selectedCategory = data.category_list[0].name;
                            }
                        }
                    })
                    .catch(error => {
                        console.error('加载分类列表失败:', error);
                        this.showError = true;
                        this.errorMessage = '加载分类列表失败，请稍后重试';
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },
            
            // 切换标签页
        switchTab(tabId) {
            this.activeTab = tabId;
            // 重置当前标签页的状态
            this.resetTabStatus(tabId);
        },
            
            // 重置标签页状态
            resetTabStatus(tabId) {
                if (tabId === 'file') {
                    this.fileStatus = '';
                    this.fileStatusColor = '';
                    this.uploadedFiles = [];
                } else if (tabId === 'text') {
                    this.textStatus = '';
                    this.textStatusColor = '';
                    this.savedTextFiles = [];
                } else if (tabId === 'image') {
                    this.imageStatus = '';
                    this.imageStatusColor = '';
                    this.uploadedImages = [];
                } else if (tabId === 'url') {
                    this.urlStatus = '';
                    this.urlStatusColor = '';
                    this.parsedUrls = [];
                }
            },
            
            // 文件上传功能
            uploadFiles() {
                if (!this.files || this.files.length === 0) {
                    this.fileStatus = '请选择文件';
                    this.fileStatusColor = 'danger';
                    return;
                }

                this.fileUploading = true;
                this.fileStatus = '上传中...';
                this.fileStatusColor = '';

                const formData = new FormData();
                for (let i = 0; i < this.files.length; i++) {
                    formData.append('files', this.files[i]);
                }
                
                // 添加分类到formData
                if (this.selectedCategory) {
                    formData.append('category', this.selectedCategory);
                }

                fetch('/embed/doc', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.fileStatus = `上传成功! 共上传 ${data.total_files} 个文件`;
                        this.fileStatusColor = 'success';
                        // 清空文件输入
                        const fileInput = document.getElementById('file');
                        if (fileInput) fileInput.value = '';
                        this.files = null;
                        
                        // 更新已上传文件列表
                        if (data.results && data.results.length > 0) {
                            this.uploadedFiles = data.results.filter(result => result.success).map(result => ({
                                original_name: result.original_filename || result.filename || '未知文件名',
                                saved_name: result.saved_filename || '未知保存文件名'
                            }));
                        }
                    } else {
                        let errorMsg = `上传失败: ${data.message}\n`;
                        data.results.forEach(result => {
                            if (!result.success) {
                                const displayFilename = result.original_filename || result.filename || '未知文件名';
                                errorMsg += `- ${displayFilename}: ${result.message}\n`;
                            }
                        });
                        this.fileStatus = errorMsg;
                        this.fileStatusColor = 'danger';
                    }
                })
                .catch(error => {
                    this.fileStatus = '上传失败: ' + error;
                    this.fileStatusColor = 'danger';
                })
                .finally(() => {
                    this.fileUploading = false;
                });
            },
            
            // 文本嵌入功能
            embedText() {
                if (!this.textContent.trim()) {
                    this.textStatus = '请输入文本内容';
                    this.textStatusColor = 'danger';
                    return;
                }

                this.textEmbedding = true;
                this.textStatus = '嵌入中...';
                this.textStatusColor = '';
                
                // 创建metadata对象并添加分类
                const metadata = {};
                if (this.selectedCategory) {
                    metadata.category = this.selectedCategory;
                }

                fetch('/embed/text', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ text: this.textContent, metadata: metadata })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 如果有返回的文件名，则在状态中显示
                        const statusText = data.filename ? 
                            `文本嵌入成功! 保存为: ${data.filename}` : 
                            '文本嵌入成功!';
                        this.textStatus = statusText;
                        this.textStatusColor = 'success';
                        this.textContent = '';
                        
                        // 更新已保存文本文件列表
                        if (data.filename) {
                            this.savedTextFiles = [{ saved_name: data.filename }];
                        }
                    } else {
                        this.textStatus = `嵌入失败: ${data.message}`;
                        this.textStatusColor = 'danger';
                    }
                })
                .catch(error => {
                    this.textStatus = '嵌入失败: ' + error;
                    this.textStatusColor = 'danger';
                })
                .finally(() => {
                    this.textEmbedding = false;
                });
            },
            
            // 图片嵌入功能
            embedImage() {
                if (!this.imageFiles || this.imageFiles.length === 0) {
                    this.imageStatus = '请选择图片';
                    this.imageStatusColor = 'danger';
                    return;
                }

                // 检查图片描述是否为空（去除前后空格和换行符后）
                if (!this.imageDescription.trim()) {
                    this.imageStatus = '请输入图片描述';
                    this.imageStatusColor = 'danger';
                    return;
                }

                this.imageEmbedding = true;
                this.imageStatus = `嵌入中... 共${this.imageFiles.length}张图片`;
                this.imageStatusColor = '';

                // 创建metadata对象并添加分类
                const metadata = {"description": this.imageDescription};
                if (this.selectedCategory) {
                    metadata.category = this.selectedCategory;
                }

                const formData = new FormData();
                for (let i = 0; i < this.imageFiles.length; i++) {
                    formData.append('files', this.imageFiles[i]);
                }
                formData.append('metadata', JSON.stringify(metadata));

                fetch('/embed/images', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.imageStatus = `所有图片嵌入成功! 共${data.total_files}张图片`;
                        this.imageStatusColor = 'success';
                        
                        // 更新已上传图片列表
                        if (data.results && data.results.length > 0) {
                            this.uploadedImages = data.results.filter(result => result.success).map(result => ({
                                original_name: result.original_filename || result.filename || '未知文件名',
                                saved_name: result.saved_filename || result.filename || '未知保存文件名'
                            }));
                        }
                    } else {
                        let errorMsg = `部分图片嵌入失败: ${data.message || '未知错误'}\n`;
                        if (data.results && data.results.length > 0) {
                            data.results.forEach(result => {
                                if (!result.success) {
                                    const displayFilename = result.original_filename || result.filename || '未知文件名';
                                    errorMsg += `- ${displayFilename}: ${result.message || '未知错误'}\n`;
                                }
                            });
                        }
                        this.imageStatus = errorMsg;
                        this.imageStatusColor = 'danger';
                    }
                    
                    // 清空图片输入
                    const imageInput = document.getElementById('imageFile');
                    if (imageInput) imageInput.value = '';
                    this.imageFiles = [];
                    this.imageDescription = '';
                })
                .catch(error => {
                    this.imageStatus = '嵌入失败: ' + error;
                    this.imageStatusColor = 'danger';
                })
                .finally(() => {
                    this.imageEmbedding = false;
                });
            },
            
            // 网页URL解析功能
            parseWebUrls() {
                if (!this.webUrls.trim()) {
                    this.urlStatus = '请输入网页URL';
                    this.urlStatusColor = 'danger';
                    return;
                }

                // 按行分割URL文本，并过滤掉空行和纯空格行
                const urls = this.webUrls.trim().split('\n')
                    .map(url => url.trim())
                    .filter(url => url.length > 0);

                // 验证所有URL的格式
                for (const url of urls) {
                    try {
                        new URL(url);
                    } catch (e) {
                        this.urlStatus = `URL格式错误: ${url}`;
                        this.urlStatusColor = 'danger';
                        return;
                    }
                }

                this.urlParsing = true;
                this.urlStatus = `解析中... 共${urls.length}个URL`;
                this.urlStatusColor = '';
                
                // 创建metadata对象并添加分类
                const metadata = {};
                if (this.selectedCategory) {
                    metadata.category = this.selectedCategory;
                }

                // 创建请求数据
                const requestData = {
                    urls: urls, 
                    metadata: metadata
                };

                fetch('/embed/weburl_batch', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.urlStatus = `解析完成: 成功${data.success_count}个, 失败${data.failed_count}个`;
                        this.urlStatusColor = 'success';
                        
                        // 如果有失败的URL，可以进一步处理
                        const failedUrls = data.results.filter(r => !r.success);
                        if (failedUrls.length > 0) {
                            const errorMsg = failedUrls.map(r => `${r.url}: ${r.message}`).join('\n');
                            console.error('以下URL解析失败:\n' + errorMsg);
                            
                            // 如果失败的URL较少，可以显示在状态信息中
                            if (failedUrls.length <= 3) {
                                this.urlStatus += '\n失败: ' + failedUrls.map(r => r.url).join(', ');
                            }
                        }
                        
                        // 对于成功的URL，如果有返回文件名，可以显示
                        const successfulWithFilename = data.results.filter(r => r.success && r.filename);
                        if (successfulWithFilename.length > 0 && successfulWithFilename.length <= 3) {
                            this.urlStatus += '\n已保存文件: ' + successfulWithFilename.map(r => r.filename).join(', ');
                        }
                        
                        // 更新已解析URL内容列表
                        this.parsedUrls = data.results.filter(result => result.success).map(result => ({
                            original_url: result.url || '未知URL',
                            saved_name: result.filename || '未知保存文件名'
                        }));
                        
                        // 清空输入
                        this.webUrls = '';
                    } else {
                        this.urlStatus = `批量解析失败: ${data.message}`;
                        this.urlStatusColor = 'danger';
                    }
                })
                .catch(error => {
                    this.urlStatus = '解析失败: ' + error;
                    this.urlStatusColor = 'danger';
                })
                .finally(() => {
                    this.urlParsing = false;
                });
            },
            
            // 处理文件选择变化
            onFileChange(event) {
                const files = event.target.files;
                const supportedExtensions = ['.txt', '.pdf', '.docx', '.md', '.xlsx', '.xls'];
                let hasInvalidFile = false;
                
                // 验证所有文件的格式
                for (let i = 0; i < files.length; i++) {
                    const fileExtension = '.' + files[i].name.split('.').pop().toLowerCase();
                    if (!supportedExtensions.includes(fileExtension)) {
                        hasInvalidFile = true;
                        break;
                    }
                }
                
                if (hasInvalidFile) {
                    this.fileStatus = '请选择支持的文件格式(.txt, .pdf, .docx, .md, .xlsx, .xls)';
                    this.fileStatusColor = 'danger';
                    this.files = null;
                    event.target.value = ''; // 清空文件选择
                } else {
                    this.files = files;
                    this.fileStatus = '';
                    this.fileStatusColor = '';
                }
            },
            
            // 处理图片选择变化
            onImageChange(event) {
                this.imageFiles = Array.from(event.target.files);
            },
            
            // 切换移动端菜单
            toggleMobileMenu() {
                const mobileMenu = document.getElementById('mobileMenu');
                if (mobileMenu) {
                    mobileMenu.classList.toggle('hidden');
                }
            },
            
            // 关闭错误提示
            closeError() {
                this.showError = false;
                this.errorMessage = '';
            }
        },
        computed: {
            // 获取当前激活的标签页的CSS类
            tabClasses() {
                return (tabId) => {
                    return tabId === this.activeTab ? 'tab-active' : '';
                };
            },
            
            // 获取状态信息的背景色类
            statusBackgroundClass() {
                return (statusColor) => {
                    if (statusColor === 'success') return 'bg-green-100 text-green-800';
                    if (statusColor === 'danger') return 'bg-red-100 text-red-800';
                    return 'bg-gray-100';
                };
            }
        },
        
        // 在组件挂载时加载分类列表
        mounted() {
            this.loadCategories();
            
            // 设置页面滚动效果
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    
                    const targetId = this.getAttribute('href');
                    const targetElement = document.querySelector(targetId);
                    if (targetElement) {
                        targetElement.scrollIntoView({
                            behavior: 'smooth'
                        });
                    }
                });
            });
        }
    }).mount('#app');
});